<?php
namespace Home\Controller;
use Think\Controller;
/**
 * 用户
 */
class UserController extends Controller {
	private $user;
	/**
	 * 构造函数
	 */
	public function _initialize() {
		$this->user = M('User');
	}
	/**
	 * 空操作
	 */
	public function _empty() {
		$this->redirect('User/login');
	}
	/**
	 * 登录
	 */
	public function login() {
		if (IS_POST) {
			$email = I('post.email');
			if (empty($email)) {
				$this->error('邮件地址不能为空');
			}
			if (false === is_email($email)) {
				$this->error('邮件地址不正确');
			}
			
			$password = I('post.password');
			if (empty($password)) {
				$this->error('密码不能为空');
			}
			
			$verification_code = I('post.verification_code');
			if ($verification_code != session('verification_code')) {
				$this->error('你输入的验证码不正确');
			}
			
			$map = array();
			$map['email'] = $email;
			$data = $this->user->field('uid,email_auth,email,password,auth_code,last_login_time,last_login_ip,timeout')->where($map)->find();
			if (is_null($data) || $data['email_auth'] == 0 || $password != pwd_decode($data['password'])) {
				$this->error('帐号或密码错误');
			}
			// 更新登录信息
			$data_user = array();
			$data_user['uid'] = $data['uid'];
			$data_user['login_count'] = array('exp', 'login_count+1');
			$data_user['last_login_time'] = get_time();
			$data_user['last_login_ip'] = get_client_ip(0);
			$this->user->save($data_user);
			
			unset($data['password']);
			$data['auth_code'] = pwd_decode($data['auth_code']);
			session('user', $data);
			session('pwd_timeout', NOW_TIME);
			$this->redirect('Index/index');
		}else {
			$tmp_user = I('user');
			if (is_null($tmp_user)) {
				$session_user = session('tmp_user');
				if (!is_null($session_user)) {
					$tmp_user = $session_user;
				}
			}
			$this->assign('user', $tmp_user);
			
			$this->display();
		}
	}
	/**
	 * 注册
	 */
	public function register() {
		if (IS_POST) {
			$email = I('post.email');
			if (empty($email)) {
				$this->error('邮件地址不能为空');
			}
			if (false === is_email($email)) {
				$this->error('邮件地址不正确');
			}
			
			$verification_code = I('post.verification_code');
			if ($verification_code != $_SESSION['verification_code']) {
				$this->error('你输入的验证码不正确');
			}
			
			$uid = $this->_check_email($email);
			
			$data = array();
			$data['email_auth'] = 0;
			$data['email'] = $email;
			$data['register_time'] = get_time();
			$data['register_ip'] = get_client_ip();
			if ('0' != $uid) {
				$data['uid'] = $uid;
				$result = $this->user->save($data);
			}else {
				$result = $this->user->add($data);
			}
			if ($result !== false) {
				$link = U('User/authentication', array('sign'=>pwd_authcode($email, 'ENCODE', '', 1800)), true, true);
				$register_time = get_time('Y年m月d日');
				
				$this->assign('email', $email);
				$this->assign('link', $link);
				$this->assign('register_time', $register_time);
				$body = $this->fetch('register_email');
				
				pwd_sendmail($email, C('PWD_NAME') . '注册确认', $body);
				$this->success('帐号注册成功，请到你的邮件中确认激活');
			}else {
				$this->error('帐号注册失败');
			}
		}else {
			$this->display();
		}
	}
	/**
	 * 验证码
	 */
	public function captcha() {
		$conf = array(
			's' => array(
				'width' => 250,
				'height' => 40,
				'minSize' => 20,
				'maxSize' => 22,
				'wave' => true
			),
			'm' => array(
				'width' => 130,
				'height' => 40,
				'minSize' => 14,
				'maxSize' => 16,
				'wave' => false
			),
			'n' => array(
				'width' => 100,
				'height' => 30,
				'minSize' => 12,
				'maxSize' => 12,
				'wave' => false
			),
		);
		$ini = $conf['s'];
		$captcha = new \Org\Util\Captcha();
		$captcha->width = $ini['width'];
		$captcha->height = $ini['height'];
		$captcha->resourcesPath = dirname(APP_PATH). '/Resource/Captcha';
		$captcha->session_var = 'verification_code';
		$captcha->colors = array(
			array(27, 78, 181),
			array(19, 121, 100),
			array(42, 52, 64),
			array(128, 15, 87),
			array(214, 36, 7)
		);
		$captcha->shadowColor = array(255, 255, 255);
		$captcha->lineWidth = 1;
		$captcha->fonts = array(
			'ERASDEMI' => array (
				'spacing' => 1,
				'minSize' => $ini['minSize'],
				'maxSize' => $ini['maxSize'],
				'font' => 'ERASDEMI.ttf'
			),
			'CourierNewBold' => array (
				'spacing' => -1,
				'minSize' => $ini['minSize'],
				'maxSize' => $ini['maxSize'],
				'font' => 'CourierNewBold.ttf'
			)
		);
		if (true == $ini['wave']) {
			$captcha->Yperiod = 28;
			$captcha->Yamplitude = 8;
			$captcha->Xperiod = 18;
			$captcha->Xamplitude = 4;
		}else {
			$captcha->Yperiod = 0;
			$captcha->Yamplitude = 0;
			$captcha->Xperiod = 0;
			$captcha->Xamplitude = 0;
		}
		$captcha->scale = 3;
		$captcha->im = imagecreatefromjpeg($captcha->resourcesPath . '/bg_' . mt_rand(0, 2) . '.jpg');
		
		$captcha->CreateImage();
	}
	/**
	 * 检查邮件地址是否注册
	 */
	protected function _check_email($email) {
		$map = array();
		$map['email'] = $email;
		
		$data = $this->user->where($map)->field('uid,email_auth')->find();
		if (!is_null($data)) {
			if (1 == $data['email_auth']) {
				$this->error('邮件已被注册');
			}else {
				return $data['uid'];
			}
		}
		return '0';
	}
	/**
	 * 邮件认证
	 */
	public function authentication() {
		if (IS_POST) {
			$password = I('post.password');
			if ('' == $password) {
				$this->error('密码不能为空');
			}else {
				$password_len = strlen($password);
				if (6 > $password_len) {
					$this->error('密码至少6位');
				}elseif (20 < $password_len) {
					$this->error('密码不能超过20位');
				}
				$level = 0;
				// 数字
				if (1 == preg_match('/\d/', $password)) {
					$level++;
				}
				// 小写字母
				if (1 == preg_match('/[a-z]/', $password)) {
					$level++;
				}
				// 大写字母
				if (1 == preg_match('/[A-Z]/', $password)) {
					$level++;
				}
				// 特殊字符~!@#$%^&*()_<>-
				if (1 == preg_match('/[~!@#$%^&*()_<>\-]/', $password)) {
					$level++;
				}
				if (3 > $level) {
					$this->error('密码至少包含数字、小写字母、大写字母和特殊字符的三种形式');
				}
			}
			$auth_code = I('post.auth_code');
			if ('' == $auth_code) {
				$this->error('加密KEY不能为空');
			}else {
				$auth_code_len = strlen($auth_code);
				if (32 < $auth_code_len) {
					$this->error('加密KEY不能超过32个字符');
				}
			}
			
			$uid = I('post.uid');
			$uid = pwd_authcode($uid);
			if ('' == $uid) {
				$this->error('请求参数非法');
			}
			
			$data = array();
			$data['uid'] = $uid;
			$data['email_auth'] = 1;
			$data['password'] = pwd_encode($password);
			$data['auth_code'] = pwd_encode(md5($auth_code));
			
			if ($this->user->save($data) !== false) {
				$this->success('帐号激活成功', U('User/login'));
			}else {
				$this->error('帐号激活失败');
			}
		}else {
			$sign = I('get.sign');
			$email = pwd_authcode($sign);
			if ('' == $email) {
				$this->error('激活链接已失效，请重新激活', U('User/register'));
			}
			$map = array();
			$map['email_auth'] = 0;
			$map['email'] = $email;
			$data = $this->user->where($map)->field('uid,email')->find();
			if (is_null($data)) {
				$this->error('激活链接已失效，请重新激活', U('User/register'));
			}
			$data['auth_code'] = pwd_rand_code(16);
			$this->assign('data', $data);
			$this->display();
		}
	}
	/**
	 * 忘记密码
	 */
	public function forgot() {
		if (IS_POST) {
			$email = I('post.email');
			if (empty($email)) {
				$this->error('邮件地址不能为空');
			}
			if (false === is_email($email)) {
				$this->error('邮件地址不正确');
			}
			
			$verification_code = I('post.verification_code');
			if ($verification_code != $_SESSION['verification_code']) {
				$this->error('你输入的验证码不正确');
			}
			
			$map = array();
			$map['email_auth'] = 1;
			$map['email'] = $email;
			$uid = $this->user->where($map)->getField('uid');
			if (is_null($uid)) {
				$this->error('无效的邮件地址');
			}
			$link = U('User/resetpassword', array('sign'=>pwd_authcode($email, 'ENCODE', '', 1800)), true, true);
			$current_time = get_time('Y年m月d日');
			$this->assign('email', $email);
			$this->assign('link', $link);
			$this->assign('current_time', $current_time);
			
			$body = $this->fetch('forgot_email');
			pwd_sendmail($email, '重设' . $email . '在' . C('PWD_NAME') . '的密码', $body);
			$this->success('一封重置密码的邮件已经发送到你的邮箱中，请确认查收');
		}else {
			$this->display();
		}
	}
	/**
	 * 重置密码 
	 */
	public function resetpassword() {
		if (IS_POST) {
			$password = I('post.password');
			if ('' == $password) {
				$this->error('密码不能为空');
			}else {
				$password_len = strlen($password);
				if (6 > $password_len) {
					$this->error('密码至少6位');
				}elseif (20 < $password_len) {
					$this->error('密码不能超过20位');
				}
				$level = 0;
				// 数字
				if (1 == preg_match('/\d/', $password)) {
					$level++;
				}
				// 小写字母
				if (1 == preg_match('/[a-z]/', $password)) {
					$level++;
				}
				// 大写字母
				if (1 == preg_match('/[A-Z]/', $password)) {
					$level++;
				}
				// 特殊字符~!@#$%^&*()_<>-
				if (1 == preg_match('/[~!@#$%^&*()_<>\-]/', $password)) {
					$level++;
				}
				if (3 > $level) {
					$this->error('密码至少包含数字、小写字母、大写字母和特殊字符的三种形式');
				}
			}
			
			$uid = I('post.uid');
			$uid = pwd_authcode($uid);
			if ('' == $uid) {
				$this->error('请求参数非法');
			}
			
			$data = array();
			$data['uid'] = $uid;
			$data['password'] = pwd_encode($password);
			
			if ($this->user->save($data) !== false) {
				$this->success('密码重置成功', U('User/login'));
			}else {
				$this->error('密码重置失败');
			}
		}else {
			$sign = I('get.sign');
			$map = array();
			$map['email_auth'] = 1;
			$map['email'] = pwd_authcode($sign);
			
			$data = $this->user->where($map)->field('uid,email')->find();
			if (empty($data)) {
				$this->error('链接已失效', U('User/forgot'));
			}
			
			$this->assign('data', $data);
			$this->display();
		}
	}
	/**
	 * 退出
	 */
	public function logout() {
		session('user', null);
		session('pwd_timeout', null);
		$this->redirect('User/login');
	}
}